let sortWeightId = "frm-lose-weight";
let sortTyp = 1;
$(document).ready(function () {
    $('.merger-title').hide();
    $('[data-toggle="tooltip"]').tooltip();
    //报损显示弹窗
    $('#frm-lose-model').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        var recipient = button.data('whatever'); // 解析出data-whatever内容
        if (recipient) {
            var modal = $(this);
            modal.find('.modal-title').text('Message To ' + recipient);
            modal.find('.modal-body input').val(recipient);
        }
    });

    //报损隐藏弹窗
    $('#frm-lose-model').on('hide.bs.modal', function (event) {
        $('#goods-detail-id').val("");
        $('#frm-lose-weight').val("");
        $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);
    });

    //报损下拉
    // $('#frm-lose-select').selectpicker('render');
    $("#frm-lose-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-detail-id').val(temp);
    });
});

function storageDoneCallBack(data, cancel, opt) {
    if (!cancel) {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
        }
    }
}

//回调处理
function weighRespCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log(">>>>>>>>>>称重回调");
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        $("#empty-btn").hide();
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
        }

    }
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        // dealWithError("emptyNumber",'');
    } else {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        console.log("KKKKKK:" + JSON.stringify(obj));
        if (obj.code == 1) {
        } else {

        }
    }
}

//分拣称重
function sortWeightCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
        }
    }
}

//货箱离开库位
function leaveBufferPosCallBack(data, cancel, opt) {

    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//出库到缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        merge(true, 0);
        return;
    }
    if (!cancel) {
        //todo 逻辑处理
        const obj = data.data;
        console.log("ooooooooooooo:" + JSON.stringify(obj));
        if (obj.code == 0) {
        } else {
            delResponseFromWcs(data, opt);
        }

    } else {
        //todo 按钮隐藏之类的
    }
}

function merge(flag, boxCode) {
    if (flag) {
        BootstrapDialog.confirm({
            title: "信息提示",
            message: "是否要执行临期出库操作?",
            btnCancelLabel: '返回',
            btnOKLabel: '确认',
            callback: function (result) {
                // 点击确定按钮时，result为true
                if (result) {
                    const clientId = $('#client-id').val();
                    selectFrmLossBox(flag, boxCode);
                } else {
                    parent.location.reload();
                }
            }
        });
    }
}

/**
 * 查询到达缓存位货箱商品
 * @param flag
 * @param boxCode
 */
function selectFrmLossBox(flag, boxCode) {
    $('.merger-title').show();
    const clientId = $('#client-id').val();
    const opt = {};
    const model = {};
    model['status'] = 1;
    model['type'] = 1;
    model['treated'] = false;
    model['dataType'] = "HSCK";
    model['bigProduct'] = 1;
    opt['data'] = model;
    $.ajax({
        type: "POST",
        url: "/wcs/record/untreated/list",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    initMergeBoxDetailList(data.data);
                }
            } else {
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}


function actionFormatterRemove(value, row, index, field) {
    let result = '';
    result += '<button type="button" id="' + row.id + '_entry" class="btn btn-primary" onclick="removeReturnEntry(\'' + row.id + '\')">移除</button>';
    return result;
}

function removeReturnEntry(id) {
    $('#merge-box-list').bootstrapTable('removeByUniqueId', id);
}

//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    console.log("row:" + JSON.stringify(row));
    result += '<button type="button" id="' + row.id + '_entry" class="btn btn-primary" onclick="removeFrmLoss(\'' + row.id + '\')">报损出库</button>';
    return result;
}

//展示临期商品列表
function initMergeBoxDetailList(goodsBoxDetailList) {
    $('#merge-table-list').bootstrapTable('destroy');
    $('#merge-table-list').bootstrapTable({
        data: goodsBoxDetailList,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            return temp;
        },
        onLoadSuccess: function (data) {
            $("#merge-table-list").bootstrapTable("load", goodsBoxDetailList);
        },
        columns: [{
            field: 'spuName',
            title: '商品'
        }, {
            field: 'temperatureZone',
            title: '温区'
        }, {
            field: 'supplierCode',
            title: '供应商'
        }, {
            field: 'quantity',
            title: '数量'
        }, {
            field: 'weight',
            title: '重量'
        }, {
            field: 'shelfLife',
            title: '保质期'
        }, {
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter,
        }]
    });
}

//分拣称重socketIo响应
function electronicWeightCallBack(data) {
    console.log("称重数据返回：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.weight) {
            sortWeightInfo("sort-spu-table", sortWeightId, sortTyp, 0, vc, 1);
        } else {
            console.log("分拣/报损称重异常：" + data);
        }
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
        }
    }
}

/**
 * 报损出库
 * @param id
 */
function removeFrmLoss(id) {
    const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', id);
    console.log("报损出库:" + JSON.stringify(orderRow));
    const opt = {};
    opt['data'] = orderRow;
    opt['bigProduct'] = 1;
    $.ajax({
        type: "POST",
        url: "/wcs/record/frm/loss",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                $('#merge-box-list').bootstrapTable('removeByUniqueId', id);
                $("#" + id + "_entry").attr("disabled", true);
                selectFrmLossBox(true, 0);
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
        }
    });
}